<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.7.0.min.js"></script>
</head>
<body>
    <h1>WebSocket Chat</h1>

    <div id="messages"></div>

    <input type="text" id="username" placeholder="Enter your username"><br>
    <input type="text" id="message" placeholder="Type a message...">
    <button onclick="connect()">Connect</button>
    <button onclick="login()">Login</button><p></p>
    To<input type="text" id="to">
    <button onclick="sendMessage()">Send</button>

    <button onclick="disconnect()">Disconnect</button>



    <script type="text/javascript">
        var socket;
        var messageInput = document.getElementById("message");
        var usernameInput = document.getElementById("username");
        var toInput = document.getElementById("to");
        
        function connect() {
            //socket = new WebSocket("ws://127.0.0.1:8080/chat/" + usernameInput.value); // 替换为你的 WebSocket 服务器地址
            
            
            //  使用session通信
            socket = new WebSocket("ws://127.0.0.1:8080/chat"); // 替换为你的 WebSocket 服务器地址
            socket.onopen = function () {
                console.log('Connected to the server');
            };

            socket.onmessage = function (event) {
                //var message = JSON.parse(event.data);
                //displayMessage(event.data);
                console.log(event.data);
            };

            socket.onclose = function () {
                console.log('Disconnected from the server');
            };
        }

        function disconnect() {
            if (socket != null) {
                socket.close();
            }
        }

         function sendMessage() {
        //     var messageInput = document.getElementById("message");
        //     var usernameInput = document.getElementById("username");

            var message = {
                from: usernameInput.value,
                to: toInput.value,
                msg: messageInput.value
            };

            socket.send(JSON.stringify(message));

            messageInput.value = "";
        }

        function displayMessage(message) {
            var messagesContainer = document.getElementById("messages");
            var messageElement = document.createElement("div");
            messageElement.innerHTML = "<strong>" + message.username + ": </strong>" + message.content;
            messagesContainer.appendChild(messageElement);
        }

        function login() {
            jQuery.ajax({
                url: 'chat/login',
                method: 'post',
                data: {username: usernameInput.value},
            });
        }
    </script>
</body>
</html>